package com.weijing.pretty_app.activity

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weijing.pretty_app.R
import com.weijing.pretty_app.databinding.ActivityMainBinding
import com.weijing.pretty_app.dialog.ShowLoadingDialog
import com.weijing.pretty_app.util.BluetoothSocketManager
import com.weijing.pretty_app.util.HexConverter
import com.weijing.pretty_app.util.HexDataParse
import com.weijing.pretty_app.util.KeyUtil
import com.weijing.pretty_app.util.SPUtil
import com.weijing.pretty_app.util.ToastUtils

private const val TAG = "MainActivity"

class MainActivity : BaseActivity() {

    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    override fun getMainView(): View = binding.main
    private val pwdBuffer = StringBuilder()
    private val defaultPwd = "123456"
    private var commandNum = 0  //已经初始化的数量
    private val commandAll = 17 //首页总的初始化参数数量
    private val receivedFuncCodes = mutableSetOf<String>()
    private var stopFlag = false //开机自检是否停止命令

    private val dataListener: (data: ByteArray) -> Unit = { data ->
        val data1 = HexConverter.byteArrayToHexString(data)
        Log.d(TAG, "收到蓝牙1数据: $data1")
        HexDataParse.parseHexString(data1) { funcCode, hexData ->
            when (funcCode) {
                "D1" -> {   //平板系列号
                    val snValue = HexDataParse.processNumbers(hexData)
                    SPUtil.put(KeyUtil.SAVE_DEVICES_SN, snValue)
                    Log.i(TAG, "功能码 D1 数据：${hexData} - ${snValue}")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "D2" -> {   //左手柄序列号
                    val waveLength = hexData[1].toIntOrNull()
                    // 808:0x31   ND_YAG(532):0x32  ND_YAG(755):0x33   ND_YAG(1064):0x34
                    when (waveLength) {
                        31 -> SPUtil.put(KeyUtil.WAVE_LENGTH_L, "808nm")
                        32 -> SPUtil.put(KeyUtil.WAVE_LENGTH_L, "532nm")
                        33 -> SPUtil.put(KeyUtil.WAVE_LENGTH_L, "755nm")
                        34 -> SPUtil.put(KeyUtil.WAVE_LENGTH_L, "1064nm")
                    }

                    val power = hexData[2].toIntOrNull()
                    //300W:0x30   400W:0x31  500W:0x32   600W:0x33   800W:0x34
                    //         1000W:0x35   1200W:0x36   1600W:0x37   2000W:0x38  2400W:0x39
                    when (power) {
                        30 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "300W")
                        31 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "400W")
                        32 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "500W")
                        33 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "600W")
                        34 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "800W")
                        35 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "1000W")
                        36 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "1200W")
                        37 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "1600W")
                        38 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "2000W")
                        39 -> SPUtil.put(KeyUtil.POWER_VALUE_L, "2400W")
                    }

                    val sn = hexData.subList(0, hexData.size)
                    val lSn = HexDataParse.processNumbers(sn)
                    SPUtil.put(KeyUtil.LEFT_HANDLE_SN, lSn)
                    Log.i(TAG, "功能码 D2 数据：${hexData} - ${lSn}")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "D3" -> {   //右手柄序列号
                    val waveLength = hexData[1].toIntOrNull()
                    // 808:0x31   ND_YAG(532):0x32  ND_YAG(755):0x33   ND_YAG(1064):0x34
                    when (waveLength) {
                        31 -> SPUtil.put(KeyUtil.WAVE_LENGTH_R, "808nm")
                        32 -> SPUtil.put(KeyUtil.WAVE_LENGTH_R, "532nm")
                        33 -> SPUtil.put(KeyUtil.WAVE_LENGTH_R, "755nm")
                        34 -> SPUtil.put(KeyUtil.WAVE_LENGTH_R, "1064nm")
                    }

                    val power = hexData[2].toIntOrNull()
                    //300W:0x30   400W:0x31  500W:0x32   600W:0x33   800W:0x34
                    //         1000W:0x35   1200W:0x36   1600W:0x37   2000W:0x38  2400W:0x39
                    when (power) {
                        30 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "300W")
                        31 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "400W")
                        32 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "500W")
                        33 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "600W")
                        34 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "800W")
                        35 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "1000W")
                        36 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "1200W")
                        37 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "1600W")
                        38 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "2000W")
                        39 -> SPUtil.put(KeyUtil.POWER_VALUE_R, "2400W")
                    }

                    val sn = hexData.subList(0, hexData.size)
                    val rSn = HexDataParse.processNumbers(sn)
                    SPUtil.put(KeyUtil.RIGHT_HANDLE_SN, rSn)
                    Log.i(TAG, "功能码 D3 数据：$hexData")
                    Log.i(TAG, "功能码 D3 数据11：$rSn")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "D4" -> {//左手柄发射次数
                    Log.i(TAG, "功能码 D4 数据：$hexData")
                    // 转换4字节数据为无符号32位整数
                    val number = HexDataParse.dataToUInt(hexData)
                    SPUtil.put(KeyUtil.HANDLE_SEND_COUNT_ALL_L, number)
                    Log.i(TAG, "功能码 D4 数据11：$number")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                    val aaa = SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_L)
                    Log.i(TAG, "D4--左手柄发射次数-- ${aaa}")
                }

                "D5" -> {//右手柄发射次数
                    Log.i(TAG, "功能码 D5 数据：$hexData")
                    // 转换4字节数据为无符号32位整数
                    val number = HexDataParse.dataToUInt(hexData)
                    SPUtil.put(KeyUtil.HANDLE_SEND_COUNT_ALL_R, number)
                    Log.i(TAG, "功能码 D5 数据11：$number")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                    val aaa = SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_R)
                    Log.i(TAG, "D5--右手柄发射次数-- ${aaa}")
                }

                "D6" -> {   //左手柄是否连接 00正常(空) 01就报警（非空有值）
                    val leftFlag = HexConverter.filterAndJoinDigits(hexData)
                    if (leftFlag.isNotEmpty()) {
                        runOnUiThread {
                            binding.mainllWarning1L.visibility = View.VISIBLE
                        }
                    } else {
                        runOnUiThread {
                            binding.mainllWarning1L.visibility = View.INVISIBLE
                        }
                    }

                    Log.i(TAG, "功能码 D6 数据：$hexData")
                    Log.i(TAG, "功能码 D6 数据11：$leftFlag")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "D7" -> {   //右手柄是否连接 00正常(空) 01就报警（非空有值）
                    val rightFlag = HexConverter.filterAndJoinDigits(hexData)
                    if (rightFlag.isNotEmpty()) {
//                        ImageDialogShow().showing(supportFragmentManager, "R", 1)
                        runOnUiThread {
                            binding.mainllWarning1R.visibility = View.VISIBLE
                        }
                    } else {
                        runOnUiThread {
                            binding.mainllWarning1R.visibility = View.INVISIBLE
                        }
                    }
                    Log.i(TAG, "功能码 D7 数据：$hexData")
                    Log.i(TAG, "功能码 D7 数据11：$rightFlag")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "D8" -> { //左手柄水温  00正常(空) 01就报警（有值）
                    val leftFlag = HexConverter.filterAndJoinDigits(hexData)
                    if (leftFlag.isNotEmpty()) {
                        runOnUiThread {
                            binding.mainllWarning2L.visibility = View.VISIBLE
                        }
                    } else {
                        runOnUiThread {
                            binding.mainllWarning2L.visibility = View.INVISIBLE
                        }
                    }
                    Log.i(TAG, "功能码 D8 数据：$hexData")
                    Log.i(TAG, "功能码 D8 数据11：$leftFlag")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "D9" -> {//右手柄水温  00正常(空) 01就报警（非空有值）
                    val rightFlag = HexConverter.filterAndJoinDigits(hexData)
                    if (rightFlag.isNotEmpty()) {
                        runOnUiThread {
                            binding.mainllWarning2R.visibility = View.VISIBLE
                        }
                    } else {
                        runOnUiThread {
                            binding.mainllWarning2R.visibility = View.INVISIBLE
                        }
                    }
                    Log.i(TAG, "功能码 D9 数据：$hexData")
                    Log.i(TAG, "功能码 D9 数据11：$rightFlag")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "DA" -> {   //左手柄水流量
                    val leftFlag = HexConverter.filterAndJoinDigits(hexData)
                    if (leftFlag.isNotEmpty()) {
                        runOnUiThread {
                            binding.mainllWarning3L.visibility = View.VISIBLE
                        }
                    } else {
                        runOnUiThread {
                            binding.mainllWarning3L.visibility = View.INVISIBLE
                        }
                    }
                    Log.i(TAG, "功能码 DA 数据：$hexData")
                    Log.i(TAG, "功能码 DA 数据11：$leftFlag")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "DB" -> {   //右手柄水流量
                    val rightFlag = HexConverter.filterAndJoinDigits(hexData)
                    if (rightFlag.isNotEmpty()) {
                        runOnUiThread {
                            binding.mainllWarning3R.visibility = View.VISIBLE
                        }
                    } else {
                        runOnUiThread {
                            binding.mainllWarning3R.visibility = View.INVISIBLE
                        }
                    }
                    Log.i(TAG, "功能码 DB 数据：$hexData")
                    Log.i(TAG, "功能码 DB 数据11：$rightFlag")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "DC" -> { //左手柄水位
                    val leftFlag = HexConverter.filterAndJoinDigits(hexData)
                    if (leftFlag.isNotEmpty()) {
                        runOnUiThread {
                            binding.mainllWarning4L.visibility = View.VISIBLE
                        }
                    } else {
                        runOnUiThread {
                            binding.mainllWarning4L.visibility = View.INVISIBLE
                        }
                    }
                    Log.i(TAG, "功能码 DC 数据：$hexData")
                    Log.i(TAG, "功能码 DC 数据11：$leftFlag")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "DD" -> { //右手柄水位
                    val rightFlag = HexConverter.filterAndJoinDigits(hexData)
                    if (rightFlag.isNotEmpty()) {
                        runOnUiThread {
                            binding.mainllWarning4R.visibility = View.VISIBLE
                        }
                    } else {
                        runOnUiThread {
                            binding.mainllWarning4R.visibility = View.INVISIBLE
                        }
                    }
                    Log.i(TAG, "功能码 DD 数据：$hexData")
                    Log.i(TAG, "功能码 DD 数据11：$rightFlag")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "C1" -> {//左手柄设置的报警参数 3字节
                    if (hexData.size == 3) {
                        val num1 = HexDataParse.hexByteToSignedInt(hexData[0])  //水温
                        val num2 = HexDataParse.hexByteToSignedInt(hexData[1])  //手柄头温度
                        val num3 = HexDataParse.dataToUInt(listOf(hexData[2]))  //水流
                        SPUtil.put(KeyUtil.ALARM_L_1, num1.toString())
                        SPUtil.put(KeyUtil.ALARM_L_2, num3.toString())
                        SPUtil.put(KeyUtil.ALARM_L_3, num2.toString())
                        Log.i(TAG, "功能码 C1 数据：$hexData")
                        if (receivedFuncCodes.add(funcCode)) {
                            commandNum += 1
                        }
                    }
                }

                "C2" -> {   //右手柄设置的报警参数 3字节
                    if (hexData.size == 3) {
                        val num1 = HexDataParse.hexByteToSignedInt(hexData[0])  //水温
                        val num2 = HexDataParse.hexByteToSignedInt(hexData[1])  //手柄头温度
                        val num3 = HexDataParse.dataToUInt(listOf(hexData[2]))  //水流
                        SPUtil.put(KeyUtil.ALARM_R_1, num1.toString())
                        SPUtil.put(KeyUtil.ALARM_R_2, num3.toString())
                        SPUtil.put(KeyUtil.ALARM_R_3, num2.toString())
                        Log.i(TAG, "功能码 C2 数据：$hexData")
                        if (receivedFuncCodes.add(funcCode)) {
                            commandNum += 1
                        }
                    }
                }

                "C3" -> {//左手柄设置的工作温度（1字节）
                    val value = hexData[0]
                    val num = HexDataParse.hexByteToSignedInt(value)
                    SPUtil.put(KeyUtil.HANDLE_HEAD_L, num.toString())
                    Log.i(TAG, "功能码 C3 数据：${num}")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "C4" -> {//右手柄设置的工作温度（1字节）
                    val value = hexData[0]
                    val num = HexDataParse.hexByteToSignedInt(value)
                    SPUtil.put(KeyUtil.HANDLE_HEAD_R, num.toString())
                    Log.i(TAG, "功能码 C4 数据：${num} -- ${commandNum}")
                    if (receivedFuncCodes.add(funcCode)) {
                        commandNum += 1
                    }
                }

                "C0" -> { //收到开机自检结束就通知加载框停止
                    Log.i(TAG, "功能码 C0 数据：${hexData}")
                    stopFlag = true
                    LiveEventBus.get<Boolean>(KeyUtil.CLOSE_LOADING).post(true)
                }

                else -> {
                    Log.w(TAG, "未知功能码 ${funcCode} -- ${hexData} ")
                    LiveEventBus.get<Boolean>(KeyUtil.CLOSE_LOADING).post(true)
                }
            }

            Log.i(TAG, "命令执行完了111: $commandNum")
            if (commandNum == commandAll) {
                Log.i(TAG, "接收数据齐了有17个")
                LiveEventBus.get<Boolean>(KeyUtil.CLOSE_LOADING).post(true)
            }
            Log.i(TAG, "命令执行完了222: $commandNum")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        initClick()

        binding.mainIvLanguage.setOnClickListener {
            val data = HexConverter.intTo2ByteHex(-10)
            Log.i(TAG, "结果呢-- ${data.joinToString(" ") { "%02X".format(it) }}")
        }

        binding.mainivWelcome.setOnClickListener {
            startActivity(Intent(this@MainActivity, MenuSelectActivity::class.java))
            finish()
        }

        BluetoothSocketManager.addDataReceivedListener(dataListener)

        //开机检测上一次是否链接成功过蓝牙设备 就自动取链接蓝牙设备
        tryReconnectLastDevice()
    }

    //发送开机命令
    private fun sendPowerOnCommand() {
        ShowLoadingDialog().showing(supportFragmentManager)
        binding.mainIvBluetoothIvConnect.visibility = View.VISIBLE
        val data = HexConverter.hexStringToByteArray(KeyUtil.START_TABLE_NOTICE)
        BluetoothSocketManager.send(data)
        Log.i(TAG, "已经发送开机: ${KeyUtil.START_TABLE_NOTICE}")
    }

    private fun initClick() {
        binding.mainTv1.setOnClickListener {
            setPwd("1")
        }

        binding.mainTv2.setOnClickListener {
            setPwd("2")
        }

        binding.mainTv3.setOnClickListener {
            setPwd("3")
        }

        binding.mainTv4.setOnClickListener {
            setPwd("4")
        }

        binding.mainTv5.setOnClickListener {
            setPwd("5")
        }

        binding.mainTv6.setOnClickListener {
            setPwd("6")
        }

        binding.mainTv7.setOnClickListener {
            setPwd("7")
        }

        binding.mainTv8.setOnClickListener {
            setPwd("8")
        }

        binding.mainTv9.setOnClickListener {
            setPwd("9")
        }

        binding.mainTv0.setOnClickListener {
            setPwd("0")
        }

        binding.mainTvGot.setOnClickListener {
            setPwd(".")
        }

        //清空
        binding.mainTvESC.setOnClickListener {
            pwdBuffer.clear()
            binding.mainEt.setText("")
        }
        //一次删除一个
        binding.mainTvDelete.setOnClickListener {
            if (pwdBuffer.isNotEmpty()) {
                pwdBuffer.deleteCharAt(pwdBuffer.length - 1)
                binding.mainEt.setText(pwdBuffer.toString())
            }
        }

        //重置密码
        binding.mainTvForgotPWD.setOnClickListener {
            val intent = Intent(this@MainActivity, MineActivity::class.java)
            intent.putExtra(KeyUtil.PWD_KEY, KeyUtil.PWD_VALUE)
            intent.putExtra(KeyUtil.MAIN_TO_PWD, true)
            startActivity(intent)
        }

        //登录
        binding.mainTvOK.setOnClickListener {
            val pwd = binding.mainEt.text.toString().trim()
            if (pwd.isEmpty()) {
                ToastUtils.show(getString(R.string.Login_password) + " " + getString(R.string.cannot_empty))
                return@setOnClickListener
            }

            val savePwd = SPUtil.getString(KeyUtil.LOGIN_PWD)
            if (savePwd.isNullOrEmpty()) {
                if (pwd == defaultPwd) {
                    startMenuSelectActivity()
                } else {
                    ToastUtils.show(getString(R.string.Login_password) + " Error!")
                    return@setOnClickListener
                }
            } else {
                if (savePwd == pwd) {
                    startMenuSelectActivity()
                } else {
                    ToastUtils.show(getString(R.string.Login_password) + " Error!")
                    return@setOnClickListener
                }
            }
        }

        binding.mainIvBluetooth.setOnClickListener {
            checkBluetoothAndNavigate()
        }

        LiveEventBus.get<Boolean>(KeyUtil.BLUETOOTH_CONNECT_TRUE).observeSticky(this) { flag ->
            if (flag) {
                Log.i(TAG, "收到蓝牙列表发送的跳转通知了-- $flag ")
                sendPowerOnCommand() //发送开机命令
            }
        }
    }

    private fun startMenuSelectActivity() {
        if (!stopFlag) {
            if (commandNum != commandAll) {
                ToastUtils.show(getString(R.string.params_no_init))
                return
            }
        }
        startActivity(Intent(this@MainActivity, MenuSelectActivity::class.java))
        finish()
    }

    private fun setPwd(pwd: String) {
        pwdBuffer.append(pwd)
        binding.mainEt.setText("")
        binding.mainEt.setText(pwdBuffer.toString())
    }

    private fun checkBluetoothAndNavigate() {
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null) {
            ToastUtils.show("设备不支持蓝牙")
            return
        }

        if (!bluetoothAdapter.isEnabled) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH_CONNECT
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                // 这里可以先请求权限，或者提示用户
                ToastUtils.show("需要蓝牙连接权限")
                return
            }
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBtIntent, 1002)
        } else {
            // 蓝牙已打开，直接跳转
            startDeviceActivity()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1002) {
            if (resultCode == Activity.RESULT_OK) {
                // 蓝牙成功打开，跳转扫描页面
                startDeviceActivity()
            } else {
                ToastUtils.show("蓝牙未打开，无法扫描设备")
            }
        }
    }

    private fun startDeviceActivity() {
        startActivity(Intent(this, BluetoothActivity::class.java))
    }

    //自动连接上次连接过的蓝牙设备
    private fun tryReconnectLastDevice() {
        val lastDeviceAddress = SPUtil.getString(KeyUtil.DEVICE_ADDRESS)
        if (lastDeviceAddress.isNullOrEmpty()) {
            Log.i(TAG, "上次连接的设备地址为空")
            return
        }

        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
            ToastUtils.show(getString(R.string.Bluetooth_is_not_turned_on))
            return
        }

        val bondedDevices: Set<BluetoothDevice>? =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (ContextCompat.checkSelfPermission(
                        this, Manifest.permission.BLUETOOTH_CONNECT
                    ) == PackageManager.PERMISSION_GRANTED
                ) {
                    bluetoothAdapter.bondedDevices
                } else {
                    null // 或者 return / 提示权限未授予
                }
            } else {
                bluetoothAdapter.bondedDevices
            }
        val targetDevice = bondedDevices?.firstOrNull { it.address == lastDeviceAddress }

        if (targetDevice == null) {
            Log.i(TAG,"未找到已配对的上次设备")
            return
        }

        BluetoothSocketManager.connect(this, targetDevice) { flag, _ ->
            if (flag) {
                //自动连接成功蓝牙设备
                sendPowerOnCommand() //发送开机命令
            }
        }
    }

    override fun onPause() {
        super.onPause()
        commandNum = 0
    }

    override fun onStop() {
        super.onStop()
        commandNum = 0
    }

    override fun onDestroy() {
        super.onDestroy()
        // 避免内存泄漏或多次回调
        BluetoothSocketManager.removeDataReceivedListener(dataListener)
        commandNum = 0
    }
}